package net.xumf.support.aop;

import lombok.extern.slf4j.Slf4j;
import net.xumf.support.annotation.RequestLimit;
import net.xumf.support.auth.CurrentUser;
import net.xumf.support.enums.CodeEnum;
import net.xumf.support.exception.SystemException;
import net.xumf.support.utils.FrequencyUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class RequestLimitMonitor {

    @Autowired
    private HttpServletRequest request;

    @Before("@annotation(limit)")
    public void before(final JoinPoint joinPoint, RequestLimit limit) throws SystemException {

        String loginName = CurrentUser.instance().get().getLoginName();
        String url = request.getRequestURL().toString();
        String key = loginName.concat(url);
        boolean timeOut = FrequencyUtil.getTimeOut(key) != null && System.currentTimeMillis() >= FrequencyUtil.getTimeOut(key);
        if (timeOut) {
            FrequencyUtil.setCount(key, 0);
            FrequencyUtil.setTimeOut(key, limit.time() * 1000);
        }
        long count = FrequencyUtil.increment(key, 1);
        if (count == 1) {
            FrequencyUtil.setTimeOut(key, limit.time() * 1000);
        }
        if (count > limit.count()) {
            log.warn("用户[" + loginName + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
            throw new SystemException(CodeEnum.REQUEST_LIMIT_EXCEED_ERROR);
        }
    }
}
